// ValidationAspects
// Written by Mike Saunders
// Released under Microsoft Public License (Ms-PL)
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using ValidationAspects.Sdk;

namespace ValidationAspects.Configuration
{
	public class ParameterValidation : IParameterValidation
	{
		public string Parameter { get; set; }
		public ValidationApplication Apply { get; set; }
		public List<IValidatorFactory> Validators { get; set; }

		public ParameterValidation()
		{
			Validators = new List<IValidatorFactory>();
		}

		public void Register(MethodInfo methodInfo)
		{
			Enforce.IsNotNull(methodInfo, "methodInfo");

			ParameterInfo parameterInfo = methodInfo.GetParameters().FirstOrDefault(p => p.Name == Parameter);
			if (parameterInfo == null)
				throw new ValidationConfigurationException(string.Format("Parameter [name:{0}] [method:{1}] [type:{2}] is unknown.", Parameter, methodInfo, methodInfo.DeclaringType));

			if (Apply == ValidationApplication.Replace)
				parameterInfo.ReplaceValidation(Validators);
			else
				parameterInfo.AddValidation(Validators);
		}
	}
}